package com.xhs.zdl.demo.webView;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;

import com.xhs.zdl.demo.R;

public class WebViewDemo extends AppCompatActivity {

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view_demo);

        findView();
        initView();
    }

    /**
     * 初始化操作
     */
    private void initView() {
        WebSettings webSettings = webView.getSettings();
        //打开js通道
        webSettings.setJavaScriptEnabled(true);
        //
        webView.addJavascriptInterface(new JsInterface(), "control");
        //加载
        webView.loadUrl("file:///android_asset/index.html");
    }

    /**
     * 拿到控件
     */
    private void findView() {
        webView = (WebView) findViewById(R.id.webView);
    }

    class JsInterface{

        @JavascriptInterface
        public void showToast(String toast){
            Toast.makeText(WebViewDemo.this, toast, Toast.LENGTH_SHORT).show();
            log("show toast success");
        }

        public void log(String msg){
            webView.post(new Runnable() {
                @Override
                public void run() {
                    webView.loadUrl("javascript:log('" + "msg" + "')");
                }
            });
        }
    }
}
